﻿/**
* userCtrl - AngularJS module for right sidebar.
*
*
* Credits
* =======
*
* Copyright 2015 LonghronShen <LonghronShen@Hotmail.com>
*/

function translateRolesEngligh(x) {
    switch (x) {
        case "Administator": return '管理员'; break;
        case "Carrier": return '承运商'; break;
        case "Driver": return '司机'; break;
        case "Staff": return '员工'; break;
        case "System": return '系统'; break;
        default: return '';
    }
}

(function () {
    "use strict";

    /**
     * Config
     */
    var moduleName = 'app';
    var DEFAULT_ID = '__default';

    /**
     * Module
     */
    var module;
    try {
        module = angular.module(moduleName);
    } catch (err) {
        // named module does not exist, so create one
        module = angular.module(moduleName, []);
    }

    module.controller('userCtrl', ['$scope', '$rootScope', '$state', '$ngBootbox', 'dataService', 'valueservice', 'uiGridConstants', function ($scope, $rootScope, $state, $ngBootbox, dataService, valueservice, uiGridConstants) {
        // console.info("<userCtrl> Defining userCtrl...");
        window.localStorage.id = null;
        window.localStorage.carCode = null;

        $scope.searchingKeyword = "";
        //$scope.searchingRoleId = "";
        $scope.searchingCarcode = "";
        $scope.searchingDriverName = "";
        $scope.searchingPhoneNumber = "";
        $scope.searchingApplicationStartTime = "";
        $scope.searchingApplicationEndTime = "";
        $scope.searchingState = '2';
        $scope.searchingEnableState = 0;
        $scope.searchingStartTime = "";
        $scope.searchingEndTime = '';

        var orderBy = $scope.orderBy = "";
        var acs = $scope.acs = 0;
        var skip = $scope.skip = 0;
        var count = $scope.count = 10;
        
        //角色
        $scope.roles = [];
        var str = [];

        //审核状态枚举
        $scope.checkState = valueservice.getRealNameState().slice(1);
        $scope.selectedUser = {};
        //初始化列表
        var loadUsers = function (keyword,realName,phoneNumber, carCode, startTime, endTime,applicationStartTime,applicationEndTime,isEnabled, state, useCache, orderBy,acs,skip, count) {
            dataService.getUsers(keyword, realName, phoneNumber, carCode, startTime, endTime, applicationStartTime, applicationEndTime, isEnabled, state, useCache == null ? false : useCache, orderBy, acs,skip, count).then(function (res) {
                res = res.data || { Response: { Output: { List: [], Total: 0 } } };
                res.Response = res.Response || { Output: { List: [], Total: 0 } };
                res.Response.Output = res.Response.Output || { List: [], Total: 0 };
                // console.info("loadUsers: getUsers returned: ", res);
                var list = res.Response.Output.List;
                // console.info("loadUsers: list: ", list);
                for (var i = 0; i < list.length; i++) {
                    list[i].Id = i + 1 + skip;
                    list[i].RealNameState = valueservice.getRealNameState()[list[i].RealNameState].text;
                    //list[i].roles = translateRealRoles(list[i].Roles);
                    list[i].isLockedout = list[i].IsLockedout;
                    list[i].IsLockedout = (list[i].IsLockedout == true) ? '是' : ((list[i].IsLockedout == false) ? '否' : '');
                    list[i].CarLength = valueservice.getCarLength()[list[i].CarLength].text;
                    list[i].CarType = valueservice.getCarType()[list[i].CarType].text;
                    list[i].CertificationApplicationTime = list[i].CertificationApplicationTime.replace(/T/, " ").replace(/Z/, "");
                    list[i].CertificationTime = list[i].CertificationTime.replace(/T/, " ").replace(/Z/, "");
                }
                //$scope.gridApi.grid.options.totalItems = res.result.total;
                $scope.gridApi.grid.options.totalItems = res.Response.Output.Total;
               
                // console.info("loadUsers: list test1: ", list);
                $scope.userList = { data: list };
                var currentPage = $scope.gridApi.grid.options.paginationCurrentPage;
                var totalPages = $scope.gridApi.pagination.getTotalPages();
                if (totalPages < currentPage) { $scope.gridApi.grid.options.paginationCurrentPage = 1; };
                $scope.seeks = false;
            }, function (rej) {
                $ngBootbox.alert(rej);
                $scope.seeks = false;
            });
        };

        //分页初始化
        var paginationOptions = {
            pageNumber: 0,
            pageSize: 10,
            currentPage: 1,
            sort: null,
            useCache: true
        };
        var _userList = $scope.userList = {
            data: [],
            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "序号", field: 'Id', enableColumnMenu: false, },
                {
                    displayName: "手机号码", field: 'PhoneNumber', enableColumnMenu: false, cellTooltip:
                true, headerTooltip: true, enableSorting: true
                },
                { displayName: "车牌号", field: 'CarNumber', enableColumnMenu: false },
                { displayName: "司机姓名", field: 'RealName', enableColumnMenu: false },
                { displayName: "车型", field: 'CarType', enableColumnMenu: false },
                { displayName: "车长", field: 'CarLength', enableColumnMenu: false },
                //{ displayName: "用户名", field: 'UserName', enableColumnMenu: false },
                { displayName: '申请认证时间', field: 'CertificationApplicationTime', enableColumnMenu: false, },
                { displayName: '认证通过时间', field: 'CertificationTime', enableColumnMenu: false, },
                { displayName: '认证状态', field: 'RealNameState', enableColumnMenu: false, },
                { displayName: '禁用状态', field: 'IsLockedout', enableColumnMenu: false, },
                //{ displayName: '角色', field: 'roles', enableColumnMenu: false },
                {
                    displayName: "操作",
                    field: '操作',
                    cellFilter: 'checkmark',
                    cellTemplate: '../../../tpl/app_management_user_table_cell.html',
                    enableColumnMenu: false
                }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridApi.core.on.sortChanged($scope, $scope.sortChanged);
                $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.OPTIONS);
                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    paginationOptions.pageNumber = newPage * pageSize - pageSize;
                    paginationOptions.pageSize = pageSize;
                    paginationOptions.currentPage = newPage;
                    $scope.gridApi.grid.options.paginationCurrentPage = newPage;
                    $scope.skip = paginationOptions.pageNumber;
                    $scope.count = paginationOptions.pageSize;
                    loadUsers($scope.searchingKeyword,$scope.searchingDriverName,$scope.searchingPhoneNumber,$scope.searchingCarcode,$scope.searchingStartTime,$scope.searchingEndTime,$scope.searchingApplicationStartTime,$scope.searchingApplicationEndTime,$scope.searchingEnableState,$scope.searchingState,
                         paginationOptions.useCache, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                    paginationOptions.useCache = true;
                });
            }
        };
        //排序
        $scope.sortChanged = function (grid, sortColumns) {
            if (sortColumns.length === 0) {
                loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
            } else {
                switch (sortColumns[0].sort.direction) {
                    case "asc":
                        $scope.orderBy = sortColumns[0].name;
                        $scope.acs = 2;
                        loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                        break;
                    case "desc":
                        $scope.orderBy = sortColumns[0].name;
                        $scope.acs = 1;
                        loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                        break;
                    case undefined:
                        loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                        break;
                }
            };
        };

        loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            true, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);

        $scope.seeks = true;
        //查询调用
        $scope.queryUsers = function () {
            $scope.seeks = true;
            paginationOptions.pageNumber = 0;
            paginationOptions.currentPage = 1;
            paginationOptions.useCache = false;
            loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, '', 0, paginationOptions.pageNumber, paginationOptions.pageSize);
        };
        //角色
        //dataService.getUserRoles().then(function (res) {

        //    // console.info("getUserRoles returned: ", res.data.Response.UserRoles);
        //    for (var m = 0; m < res.data.Response.UserRoles.length; m++) {
        //        var StrElement = { 'Id': res.data.Response.UserRoles[m].Id, 'Name': res.data.Response.UserRoles[m].Name, 'chineseName': translateRolesEngligh(res.data.Response.UserRoles[m].Name) };
        //        str.push(StrElement);
        //    }
        //    // console.info('str',str);
        //    $scope.roles = str;
        //}, function (rej) {
        //    $ngBootbox.alert(rej);
        //});

        ////角色转换
        //function translateRoles(id) {
        //    // console.info("$scope.roles1 ", $scope.roles);
        //    var UserRole = $scope.roles;
        //    for (var z = 0; z < UserRole.length; z++) {
        //        if (id == UserRole[z].Id) {
        //            return UserRole[z].chineseName;
        //        }
        //    }
        //}
        //function translateRealRoles(roleList) {
        //    // console.info('role list', roleList);
        //    for (var j = 0; j < roleList.length; j++) {
        //        var name = translateRoles(roleList[j]) + ' ';
        //        return name;
        //    }
        //};
        //end角色转换
        

        //启用
        $scope.disabledStar = function (userId) {
            $ngBootbox.confirm('是否启用该权限').then(function () {
                dataService.setAccountLockoutState(userId, false).then(function (res) {
                    paginationOptions.useCache = false;
                    //$scope.gridApi.pagination.raise.paginationChanged(paginationOptions.currentPage, paginationOptions.pageSize);
                    loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, '', 0, paginationOptions.pageNumber, paginationOptions.pageSize);
                }, function (rej) {
                    $ngBootbox.alert(rej)
                });
            }, function () {
                return;
            });
        }
        //禁用
        $scope.disableUser = function (userId) {
            $ngBootbox.confirm('是否禁用该用户').then(function () {
                dataService.setAccountLockoutState(userId, true).then(function (res) {
                    paginationOptions.useCache = false;
                    //$scope.gridApi.pagination.raise.paginationChanged(paginationOptions.currentPage, paginationOptions.pageSize);
                    loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, '', 0, paginationOptions.pageNumber, paginationOptions.pageSize);
                }, function (rej) { $ngBootbox.alert(rej); })
            }, function () {
                return;
            });
        };
        
        //跳转到账户信息
        $scope.linkToAccountInfo = function (user) {
            $state.go("app.management.account_info", { id: user.UserId, carNumber: user.CarNumber });
        }

    }]);
})();